<template>
  <div class="box">
    <!-- 搜索 -->

    <!-- 导入 -->
    <div class="export">
      <div class="upload">
        <template>
          <download-excel class="export-excel-wrapper" :data="excelForm" :fields="json_fields" :header="excelTitle"
            name="设备列表.xls">
            <el-button type="primary" @click="handleExport">导出设备数据</el-button>
          </download-excel>
        </template>
      </div>
      <div class="search-box">
        <div>
          <el-input v-model="inputImei" placeholder="请输入imei编码" maxlength="6" />
        </div>
        <div>
          <el-button type="primary" icon="el-icon-search" class="search-but" @click="searchSubmit()">搜索</el-button>
          <el-button type="success" @click="getList(1)">刷新</el-button>
        </div>
      </div>
    </div>
    <!-- 表格 -->
    <el-table v-loading="loading" border style="width: 100%" :data="tableData">
      <!-- <el-table-column prop="device_id" label="#ID" align="center" width="50"></el-table-column> -->
      <el-table-column prop="device_name" label="设备别名" align="center" show-overflow-tooltip />
      <el-table-column prop="device_imei" label="设备编码" align="center" show-overflow-tooltip />
      <el-table-column prop="itime" label="创建时间" align="center" />
      <el-table-column prop="address" label="最近一次上报地址" align="center" show-overflow-tooltip />
      <!-- <el-table-column prop="version" label="固件版本" align="center" width="50"></el-table-column> -->
      <el-table-column prop="is_line" label="在线状态" align="center" width="100">
        <template slot-scope="scope">
          <el-tag :type="scope.row.is_line === 1 ? 'success' : 'primary'"
            disable-transitions>{{ scope.row.is_line === 1 ? '在线':'离线' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="device_bind_status" label="绑定状态" align="center" width="100">
        <template slot-scope="scope">
          {{ scope.row.device_bind_status === 1?'已绑定':'未绑定' }}
        </template>
      </el-table-column>
      <!-- <el-table-column prop="device_bind_way" label="绑定方式" align="center">
        <template slot-scope="scope">
          {{scope.row.device_bind_way === 2?scope.row.mobile:scope.row.openid}}
        </template>
      </el-table-column> -->
      <el-table-column prop="device_status" label="设备状态" align="center">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.device_status" :active-text="scope.row.device_status === 1 ? '启用':'停用'"
            :active-value="1" :inactive-value="2"
            @change="switchChange([scope.row.device_status,scope.row.device_id])" />
        </template>
      </el-table-column>
      <el-table-column prop="cable" label="设备电量" align="center">
        <template slot-scope="scope">
          {{ power(scope.row.cable) }}%
        </template>
      </el-table-column>
      <el-table-column prop="temp" label="设备温度" align="center">
        <template slot-scope="scope">
          {{ scope.row.temp }}℃
        </template>
      </el-table-column>
      </el-table-column>
      <el-table-column label="操作" align="center" fixed="right" width="260px">
        <template slot-scope="scope">
          <el-button v-if="scope.row.device_bind_status == 1" size="mini" type="warning"
            @click="handleUnBinDing(scope.row)">解绑</el-button>
          <el-button size="mini" type="danger" @click="handleDel(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 翻页 -->
    <el-pagination class="pagination" background layout="total,prev, pager, next" :total="total" :page-size="pageSize"
      @current-change="handleCurrentChange" />
  </div>
</template>
<script>
  import {
    deviceList,
    deviceStatusSwitch,
    delDevice,
    importExcel,
    exportExcel
  } from '@/api/device.js'
  import {
    unBinding
  } from '@/api/user.js'
  import {
    getToken
  } from '@/utils/auth'
  import store from '@/store'
  export default {
    data() {
      return {
        tableData: [],
        total: 0,
        pageSize: 10,
        currPage: 1,
        loading: false,
        inputImei: '',
        token: {
          'x-csrf-token': getToken()
        },
        action: process.env.VUE_APP_BASE_API + 'admin/import',
        // excel
        json_fields: {
          'ID': 'id',
          '设备别名': 'device_name',
          '添加时间': 'itime',
          '最近一次上报地址': 'address',
          '固件版本': 'version',
          '网卡状态': 'network_card',
          '设备编码': 'device_imei'
        },
        excelTitle: '所有设备列表',
        excelForm: []
      }
    },
    created() {
      this.getList(1)
    },
    methods: {
      power(v) {
        let p = ((v - 800) / 240 * 100).toFixed(1);
        if (p <= 0) {
          return 0
        } else if (p >= 100) {
          return 100
        } else {
          return p
        }
      },
      // 列表
      getList(num) {
        this.loading = true
        deviceList({
          page: this.currPage,
          size: this.pageSize,
          imei: this.inputImei
        }).then(res => {
          this.loading = false
          this.tableData = res.data.list
          this.total = res.data.total_num
        })
      },
      // 当前页改变时触发 跳转其他页
      handleCurrentChange(val) {
        this.currPage = val
        this.getList(val)
      },
      // 搜索
      searchSubmit() {
        this.loading = true
        deviceList({
          page: this.currPage,
          size: this.pageSize,
          imei: this.inputImei
        }).then(res => {
          this.loading = false
          this.tableData = res.data.list
          this.total = res.data.total_num
        })
      },
      // 设备开关
      switchChange(e) {
        deviceStatusSwitch({
          switch: e[0],
          id: e[1]
        }).then((res) => {
          if (res.code == 1) {
            if (e[0] == 2) {
              var msg = '停用成功'
            } else {
              var msg = '启用成功'
            }
            this.$message.success(msg)
          } else {
            this.$message.error(res.msg)
          }
        })
      },
      // 解绑
      handleUnBinDing(row) {
        var device_id = row.device_id
        this.$confirm('此操作将同步清除所有上报数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          unBinding({
            device_id: device_id
          }).then((res) => {
            if (res.code == 1) {
              this.$message.success('解绑成功')
            } else {
              this.$message.error(res.message)
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消操作'
          })
        })
      },
      // 删除
      handleDel(row) {
        var device_id = row.device_id
        this.$confirm('此操作将删除设备, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          delDevice({
            id: device_id
          }).then((res) => {
            if (res.code == 1) {
              this.$message.success('删除成功')
              // 刷新当前页
              this.getList(1)
            } else {
              this.$message.error(res.message)
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消操作'
          })
        })
      },
      // 导入
      handleUploadSuccess(response, file, fileList) {
        // console.log(file)
        // console.log(response)
        if (response.code == 1) {
          this.$message.success('上传成功')
        } else {
          this.$message.error(response.message)
        }
        // 在这里可以使用axios等网络请求库将文件发送到后端
      },
      beforeUpload(file) {
        // console.log(file.type)
        const isXlsx = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        const isLt5M = file.size / 1024 / 1024 < 5
        if (!isXlsx) {
          this.$message.error('只能上传xlsx文件')
          return false
        }
        if (!isLt5M) {
          this.$message.error('上传文件大小不能超过 5 MB')
          return false
        }
        return true
      },
      handleExport() {
        const loadingall = this.$loading({
          lock: true,
          text: '⏬：数据导出中，请等待...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        exportExcel().then(res => {
          if (res.data.length == 0) {
            loadingall.close()
            this.$message.warning('数据为空！')
          } else {
            loadingall.close()
            this.excelForm = res.data
          }
        })
      }
    }
  }
</script>
<style lang="scss" scoped>
  .box {
    margin: 20px 50px;
  }

  .button,
  .el-input {
    margin-bottom: 20px;
  }

  .pagination {
    margin-top: 20px;
    text-align: right;
  }

  .search-box {
    display: flex;
    justify-content: flex-end;
  }

  .search-but {
    height: 38px;
  }

  .el-input {
    width: 200px;
    height: 30px;
    margin-right: 10px;
  }

  .export {
    display: flex;
    justify-content: space-between;
  }

  .upload {
    margin-right: 10px;
    margin-bottom: 10px;
  }
</style>